#include "CTokenSplitter.h"
#include "..\mem\g_mem.h"

CTokenSplitter::CTokenSplitter()
{
	m_tokenCount = 0;
	m_tokens = NULL;
}

CTokenSplitter::CTokenSplitter(char *s)
{
	m_tokenCount = 0;
	m_tokens = NULL;
	
	split(s);
}

void CTokenSplitter::releaseTokens()
{
	if (m_tokenCount>0)
	{
		for (int i = 0; i < m_tokenCount; i++)
			g_free(m_tokens[i]);
		
		g_free(m_tokens);
		m_tokenCount = 0;
	}
}

CTokenSplitter::~CTokenSplitter()
{
	releaseTokens();
}

int CTokenSplitter::isValidChar(char c)
{
	return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '_') || (c == '-') || (c == '.'));
}

int CTokenSplitter::skipWhiteSpace(char *s, int p)
{
	do
	{
		if (!isValidChar(s[p]))
			p++;
		else
			return p;
	}
	while ((s[p] != 0) &&(p < MAX_STRING_SIZE));
	
	return -1;
}

int CTokenSplitter::skipWord(char *s, int p)
{
	do
	{
		if (isValidChar(s[p]))
			p++;
		else
			return p;
	}
	while ((s[p] != 0) &&(p < MAX_STRING_SIZE));
	
	return -1;
}

int CTokenSplitter::split(char *s)
{
	int p = 0;
	int p2;
	
	releaseTokens();
	
	while (p >= 0)
	{
		p = skipWhiteSpace(s, p);
		if (p >= 0)
		{
			m_tokenCount++;
			p = skipWord(s, p);
		}
	}
	
	g_allocv(m_tokens, char*, m_tokenCount);
	
	p = 0;
	for (int i = 0; i < m_tokenCount; i++)
	{
		p = skipWhiteSpace(s, p);
		p2 = skipWord(s, p);
		g_allocv(m_tokens[i], char, p2 - p + 1);
		g_strncpy(m_tokens[i], s + p, p2 - p);
		m_tokens[i][p2 - p] = 0;
		
		p = p2;
	}
	
	
	return m_tokenCount;
}

int CTokenSplitter::getTokenCount()
{
	return m_tokenCount;
}

const char *CTokenSplitter::getToken(int pos)
{
	if ((pos >= 0) &&(pos < m_tokenCount))
		return m_tokens[pos];
	
	return (char*)0;
}